⚡️ Speed up function _get_pyplot_commands by 21%
#254
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 21% (0.21x) speedup for
_get_pyplot_commandsinlib/matplotlib/pyplot.py⏱️ Runtime :
1.87 milliseconds→1.55 milliseconds(best of70runs)📝 Explanation and details
The optimization achieves a 21% speedup by reducing function call overhead and attribute lookups within loops.
Key optimizations applied:
Eliminated repeated attribute lookups in
_get_pyplot_commands(): The original code calledstr.startswith,inspect.isfunction, andinspect.getmodulerepeatedly within the loop. The optimized version caches these as local variables (startswith,isfunction,getmodule), avoiding costly attribute resolution on each iteration.Replaced generator expression with direct list building: Instead of using
sorted(generator), the optimization builds a results list directly and callssort()once at the end. This reduces memory allocation overhead and is more efficient for the sorting operation.Cached
globals().items(): Storing the result inglobals_itemsavoids repeated function calls.Why this matters for matplotlib:
The
_get_pyplot_commands()function is called byget_plot_commands(), which introspects the pyplot module to find plotting functions. Given that matplotlib is a widely-used plotting library, this function could be called frequently during module initialization or interactive sessions.Performance characteristics from tests:
The optimization shows consistent 19-22% improvements across all test scenarios, including:
The optimization is particularly effective because it reduces the per-iteration cost in what can be a substantial loop over the module's global namespace, making it scale well as the number of functions increases.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_pyplot.py::test_doc_pyplot_summary🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_get_pyplot_commands-mjb56gckand push.